import React, { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';

export default function Enrollment() {
  const { user } = useAuth();
  const [courses, setCourses] = useState([]);
  const [enrolled, setEnrolled] = useState([]);
  const [selectedCourse, setSelectedCourse] = useState('');
  const [gradeStudentId, setGradeStudentId] = useState('');
  const [gradeCourseId, setGradeCourseId] = useState('');
  const [gradeValue, setGradeValue] = useState('');

  const fetchCourses = async () => {
    const res = await fetch('/api/course');
    const data = await res.json();
    if (data.success) setCourses(data.data);
  };
  const fetchEnrolled = async (sid) => {
    if (!sid) return;
    const res = await fetch(`/api/enroll/${sid}`);
    const data = await res.json();
    if (data.success) setEnrolled(data.data);
  };

  useEffect(() => {
    fetchCourses();
  }, []);
  useEffect(() => {
    if (user && user.student_id) fetchEnrolled(user.student_id);
  }, [user]);

  const handleEnroll = async (e) => {
    e.preventDefault();
    if (!user || !selectedCourse) {
      alert('请选择课程');
      return;
    }
    const res = await fetch('/api/enroll', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ student_id: user.student_id, course_id: selectedCourse })
    });
    const data = await res.json();
    if (data.success) {
      fetchEnrolled(user.student_id);
      setSelectedCourse('');
    } else {
      alert(data.message || '选课失败');
    }
  };

  const handleGrade = async (e) => {
    e.preventDefault();
    if (!user || !user.is_admin || !gradeStudentId || !gradeCourseId || gradeValue === '') {
      alert('请填写完整信息');
      return;
    }
    const res = await fetch('/api/grade', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ student_id: gradeStudentId, course_id: gradeCourseId, grade: gradeValue })
    });
    const data = await res.json();
    if (data.success) {
      alert('成绩录入成功');
      setGradeStudentId('');
      setGradeCourseId('');
      setGradeValue('');
    } else {
      alert(data.message || '录入失败');
    }
  };

  return (
    <div className="card">
      <h2>选课与成绩</h2>
      <form onSubmit={handleEnroll} style={{ marginBottom: 20, display: 'flex', gap: 12 }}>
        <select value={selectedCourse} onChange={e => setSelectedCourse(e.target.value)}>
          <option value="">选择课程</option>
          {courses.map(c => (
            <option key={c.course_id} value={c.course_id}>{c.name}（{c.course_id}）</option>
          ))}
        </select>
        <button type="submit">选课</button>
      </form>
      <h3>已选课程与成绩</h3>
      <table>
        <thead>
          <tr><th>课程号</th><th>课程名称</th><th>院系</th><th>学分</th><th>成绩</th></tr>
        </thead>
        <tbody>
          {enrolled.map(e => (
            <tr key={e.course_id}>
              <td>{e.course_id}</td>
              <td>{e.course_name}</td>
              <td>{e.department_name}</td>
              <td>{e.credit}</td>
              <td>{e.grade !== null ? e.grade : '未录入'}</td>
            </tr>
          ))}
        </tbody>
      </table>
      {user && user.is_admin ? (
        <form onSubmit={handleGrade} style={{ marginTop: 24, display: 'flex', gap: 12, alignItems: 'center' }}>
          <input type="text" placeholder="学生学号" value={gradeStudentId} onChange={e => setGradeStudentId(e.target.value)} />
          <input type="text" placeholder="课程号" value={gradeCourseId} onChange={e => setGradeCourseId(e.target.value)} />
          <input type="number" placeholder="成绩" value={gradeValue} onChange={e => setGradeValue(e.target.value)} style={{ width: 80 }} />
          <button type="submit">录入成绩</button>
        </form>
      ) : null}
    </div>
  );
} 